package com.platform.cdcs.fragment.custom;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.adapter.ProductItemAdatper;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.DisProductList;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.model.SubBUItem;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.platform.cdcs.widget.ChooseWindow;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.fragment.SearchListener;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/28.
 */
public class ProSearchListFragment extends BaseFragment {

    private ObservableXListView slideListView;
    private ProductItemAdatper adapter;
    private String code = "";
    private TextView lineTV, lineNameTV;

    private String mClass;
    private TextView titleView;
    private List<ChooseItem> subBuList;
    private int pageIndex = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new ProductItemAdatper(getContext());
        adapter.setModel(2);
        adapter.hideUnit();
        mClass = getArguments().getString("class");
        adapter.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProductList.ProductItem item=(ProductList.ProductItem)view.getTag(R.mipmap.ic_launcher);
                RefershEvent event=new RefershEvent();
                try {
                    event.mclass=Class.forName(mClass);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                event.oclass=ProSearchListFragment.this.getClass();
                event.bundle=new Bundle();
                event.bundle.putSerializable("model",item);
                EventBus.getDefault().post(event);
                getActivity().finish();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initView(View view) {
        titleView = (TextView) getActivity().findViewById(R.id.title);
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
//        setHasOptionsMenu(true);
        setTitle("选择产品");

        view.findViewById(R.id.search_layout).setVisibility(View.VISIBLE);
        initSearch(view.findViewById(R.id.search), "输入产品代码搜索", new SearchListener() {
            @Override
            public void search(String s) {
                pageIndex = 1;
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestList(true);
            }
        }, view.findViewById(R.id.cancel));

        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.choose_item, null);
        headerView.findViewById(R.id.img).setVisibility(View.GONE);
        lineTV = (TextView) headerView.findViewById(R.id.title);
        lineTV.setText(ViewTool.makeArrorDown("全部产品线", "▼"));


        lineTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showChooseWindow(titleView);
            }
        });


        slideListView = (ObservableXListView) view.findViewById(android.R.id.list);
        slideListView.addHeaderView(headerView);
        slideListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestList(false);
            }

            @Override
            public void onLoadMore() {
                requestList(false);
            }
        });
        slideListView.setAdapter(adapter);
        requestList(true);
    }

//    @Override
//    protected void initMenu(Menu menu, MenuInflater inflater) {
////        menu.add(0, 0, 0, "搜索").setIcon(R.mipmap.icon_search).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
////            @Override
////            public boolean onMenuItemClick(MenuItem menuItem) {
////                FragmentUtil.navigateToInNewActivity(getActivity(), ProSearchFragment.class, null);
////                return false;
////            }
////        }).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestList(boolean show) {
        if (show) {
            showLoadImg();
        }
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "4");
        map.put("subBU", code);
        map.put("itemCode", searchET.getText().toString().trim());
        map.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
        map.put("pageIndex", String.valueOf(pageIndex));
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                slideListView.stopRefresh();
                slideListView.stopLoadMore();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    slideListView.stopRefresh();
                    slideListView.stopLoadMore();
                    Type type = new TypeToken<BaseObjResponse<ItemList>>() {
                    }.getType();
                    BaseObjResponse<ItemList> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        adapter.addAll(response.getResult().getItemList());
                        adapter.notifyDataSetChanged();
                        if (response.getResult().getItemList().size() == Constant.PAGE_SIZE) {
                            pageIndex++;
                            slideListView.setPullLoadEnable(true);
                        } else {
                            slideListView.setPullLoadEnable(false);
                        }
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析数据失败");
                }
            }
        });
    }

    private void requestSubBu() {
        showLoadImg();
        getHttpClient().post().url(Constant.SUBBU_LST).params(Constant.makeParam(new HashMap<String, String>())).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<SubBUItem.SubBUList>>() {
                    }.getType();
                    BaseObjResponse<SubBUItem.SubBUList> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        subBuList = new ArrayList<ChooseItem>();
                        ChooseItem item = new ChooseItem();
                        item.setTitle("全部产品线");
                        item.setTime("");
                        item.setIsCheck(true);
                        subBuList.add(item);
                        for (SubBUItem sub : response.getResult().getObjList()) {
                            item = new ChooseItem();
                            item.setTitle(sub.getSubBUCode());
                            item.setTime(sub.getSubBU());
                            subBuList.add(item);
                        }
                        showChooseWindow(titleView);
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private void showChooseWindow(View view) {
        if (subBuList == null || subBuList.size() == 0) {
            requestSubBu();
            return;
        }
        final ChooseWindow window = new ChooseWindow(getContext());
        window.setType(0);
        window.setData(subBuList, "产品线", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
                code = window.getChoose();
                if (!TextUtils.isEmpty(code)) {
                    if (code.contains(",")) {
                        lineTV.setText(ViewTool.makeArrorDown(code.substring(0, code.indexOf(",")) + "等", "▼"));
                    } else {
                        lineTV.setText(ViewTool.makeArrorDown(code, "▼"));
                    }
                } else {
                    lineTV.setText(ViewTool.makeArrorDown("全部产品线", "▼"));
                }
                pageIndex = 1;
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestList(true);
            }
        });
        window.show((View) view.getParent());
    }

    private class ItemList extends MockObj {

        private List<ProductList.ProductItem> itemList;

        public List<ProductList.ProductItem> getItemList() {
            return itemList;
        }

        public void setItemList(List<ProductList.ProductItem> itemList) {
            this.itemList = itemList;
        }
    }
}
